var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    cart_list:"",
    total_goods_sum:0,
    selectAllStatus: false,
    startX: 0, //开始坐标
    startY: 0,
    onRefresh: true,

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.cart_list()
  },

  delCartItem(e) {
    const index=e.currentTarget.dataset.index;
    const id=e.currentTarget.dataset.id;
    this.data.cart_list.splice(index, 1);
    this.setData({
      cart_list: this.data.cart_list
    });
    this.delcart(id);
  },

  //删除购物车
  delcart(id){
    var that = this;
    wx.request({
      url: app.globalData.httpUrl+"api/mini/delcart",
      header: {
          'content-type': 'application/x-www-form-urlencoded','appid':app.globalData.appId
      },
      data:{id:id},
      method: 'POST',
      dataType: 'json',
      success: function (res) {
        app.cart_count()
      }
    })
  },

  checkOut(){
    var phone = '';
    if(getApp().globalData.userInfo.phone){
      phone = getApp().globalData.userInfo.phone
    }
    if(phone==''||phone==null){
      wx.showModal({
        title: '提示',
        content: '请您完善个人信息后，再进行结算哦！',
        complete: (res) => {
          if (res.confirm) {
            wx.navigateTo({
              url: '/pages/setting/addr',
            })
          }
        }
      })
      return
    }
    let cart_list = this.data.cart_list;
    var ids = '';
    var that = this;
    for(var i=0;i<cart_list.length;i++){
      if(cart_list[i]['selected']==true){
        ids += ','+Number(cart_list[i]['id'])
      }
    }
    if(ids==''){
      wx.showToast({
        title: '请选择套餐',
      })
    }else{
      wx.navigateTo({
        url: '/pages/pay/index?ids='+ids,
      })
    }
  },

  
  delcart_select(){
    let cart_list = this.data.cart_list;
    var ids = '';
    var that = this;
    for(var i=0;i<cart_list.length;i++){
      if(cart_list[i]['selected']==true){
        ids += ','+Number(cart_list[i]['id'])
      }
    }
    if(ids==''){
      wx.showToast({
        title: '请选择套餐',
      })
    }else{
      wx.showModal({
        title: '确认删除操作', // 对话框的标题
        content: '您确定要执行此操作吗？', // 对话框的内容
        showCancel: true, // 是否显示取消按钮
        cancelText: '取消', // 取消按钮的文字，最多 4 个字符
        cancelColor: '#000000', // 取消按钮的文字颜色
        confirmText: '确定', // 确定按钮的文字，最多 4 个字符
        confirmColor: '#3CC51F', // 确定按钮的文字颜色
        success: function(res) {
          if (res.confirm) {
            // 用户点击了确定按钮
            console.log('用户点击了确定');
            that.delcarts(ids)
            setTimeout(function(){
              that.cart_list()
            },1000)
            
            // 在这里执行你的逻辑，例如跳转页面、发送请求等
          } else if (res.cancel) {
            // 用户点击了取消按钮
            console.log('用户点击了取消');
            // 可以选择在这里不执行任何操作或者执行一些取消逻辑
          }
        }
      });
    }
  },

  
  //删除购物车
  delcarts(id){
    var that = this;
    wx.request({
      url: app.globalData.httpUrl+"api/mini/delcarts",
      header: {
          'content-type': 'application/x-www-form-urlencoded','appid':app.globalData.appId
      },
      data:{id:id},
      method: 'POST',
      dataType: 'json',
      success: function (res) {
        app.cart_count()
      }
    })
  },

  

  selectList(e) {
    let selectAllStatus = this.data.selectAllStatus;
    const index = e.currentTarget.dataset.index;
    let cart_list = this.data.cart_list;
    const selected = cart_list[index].selected;
    cart_list[index].selected = !selected;
    //购物车列表里的条目只要有一个取消，全选就取消
    const symbol = cart_list.some(cart => {
      return cart.selected === false;
    });
    if (symbol) {
      this.data.selectAllStatus = false;
    } else {
      this.data.selectAllStatus = true;
    }

    this.setData({
      cart_list,
      selectAllStatus: this.data.selectAllStatus
    });
    this.getTotalPrice();
  },
  getTotalPrice() {
    var that = this
    let cart_list = this.data.cart_list;
    let totalPrice = 0;
    let check_goods_sum = 0;
    let total_goods_sum = 0;
    for (let i = 0; i < cart_list.length; i++) {
      if (cart_list[i].selected) {
        check_goods_sum += 1
        totalPrice +=  Number(cart_list[i].total_price);
      }
      total_goods_sum += 1
    }
    this.setData({
      totalPrice:totalPrice.toFixed(2),
      total_goods_sum:total_goods_sum,
      goods_sum:check_goods_sum
    });

  },
  selectAll(e) {
    let selectAllStatus = this.data.selectAllStatus;
    selectAllStatus = !selectAllStatus;
    let cart_list = this.data.cart_list;
    for (let i = 0; i < cart_list.length; i++) {
      cart_list[i].selected = selectAllStatus;
    }
    this.setData({
      cart_list,
      selectAllStatus
    });
    this.getTotalPrice();
  },


  touchstart: function (e) {
    this.data.cart_list.map(item => {
      if (item.isTouchMove) {
        item.isTouchMove = false;
      }
    })
    this.setData({
      startX: e.changedTouches[0].clientX,
      startY: e.changedTouches[0].clientY,
      cart_list: this.data.cart_list
    })
  },
  //滑动事件处理
  touchmove(e) {
    var
      index = e.currentTarget.dataset.index, //当前索引
      startX = this.data.startX, //开始X坐标
      startY = this.data.startY, //开始Y坐标
      touchMoveX = e.changedTouches[0].clientX, //滑动变化坐标
      touchMoveY = e.changedTouches[0].clientY, //滑动变化坐标
      //获取滑动角度
      angle = this.angle({
        X: startX,
        Y: startY
      }, {
        X: touchMoveX,
        Y: touchMoveY
      });
    this.data.cart_list.forEach(function (v, i) {
      v.isTouchMove = false
      //滑动超过30度角 return
      if (Math.abs(angle) > 30) return;
      if (i == index) {
        if (touchMoveX > startX) //右滑
          v.isTouchMove = false
        else //左滑
          v.isTouchMove = true
      }
    })
    //更新数据
    this.setData({
      cart_list: this.data.cart_list
    })
  },
  angle(start, end) {
    var X = end.X - start.X,
      Y = end.Y - start.Y
    //返回角度 /Math.atan()返回数字的反正切值
    return 360 * Math.atan(Y / X) / (2 * Math.PI);
  },
  delCartItem(e) {
    const index=e.currentTarget.dataset.index;
    const id=e.currentTarget.dataset.id;
    console.log(index);
    this.data.cart_list.splice(index, 1);
    wx.clearStorageSync("select_num");
    this.setData({
      cart_list: this.data.cart_list
    });

    this.delcart(id);

  },

  cart_list(){
    var that = this
    wx.request({
      url: getApp().globalData.httpUrl+"api/mini/cart",
      header: {
        'content-type': 'application/x-www-form-urlencoded','appid':getApp().globalData.appId
      },
      method: 'POST',
      dataType: 'json',
      data:{user_id:getApp().globalData.userInfo.id},
      success: function(re) {
        console.log(re)
        that.setData({
          cart_list:re.data.list,
          total_goods_sum:re.data.total_goods_sum
        })
        that.getTotalPrice()
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.cart_list()
    getApp().globalData.nav = 0
    app.cart_count()
    this.setData({
      selectAllStatus: false
    })

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})